<?php
/**
 * Created by PhpStorm.
 * User: zhangrongxiang
 * Date: 2018/4/144
 * Time: 16:16
 */

/**
 * 将数据集转换成Tree（真正的Tree结构）
 * @param array $list 要转换的数据集
 * @param string $pk ID标记字段
 * @param string $pid parent标记字段
 * @param string $child 子代key名称
 * @param int $root 返回的根节点ID
 * @param bool $strict 默认严格模式
 * @return array
 */
function list2tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0, $strict = true)
{
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = &$list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parent_id = isset($data[$pid]) ? $data[$pid] : null;
            if ($parent_id === null || (String)$root === $parent_id) {
                $tree[] = &$list[$key];
            } else {
                if (isset($refer[$parent_id])) {
                    $parent = &$refer[$parent_id];
                    $parent[$child][] = &$list[$key];
                } else {
                    if ($strict === false) {
                        $tree[] = &$list[$key];
                    }
                }
            }
        }
    }
    return $tree;
}

$arr = [[
    "sys_dpt_id" => "97",
    "title" => "开发部",
    "pid" => "1",
    "update_eid" => "1",
    "update_time" => "2018-04-10 13:44:31",
],[
    "sys_dpt_id" => "25",
    "title" => "后勤部",
    "pid" => "1",
    "update_eid" => "1",
    "update_time" => "2018-03-27 13:26:41",
],[
    "sys_dpt_id" => "1",
    "title" => "海澜飞马水城旅游管理有限公司",
    "pid" => "0",
    "update_eid" => "1",
    "update_time" => "2018-03-26 16:00:31",
],[
    "sys_dpt_id" => "4",
    "title" => "服务部",
    "pid" => "1",
    "update_eid" => "1",
    "update_time" => "NULL",
],[
    "sys_dpt_id" => "18",
    "title" => "运营部",
    "pid" => "1",
    "update_eid" => "1",
    "update_time" => "2018-03-27 13:15:10",
],[
    "sys_dpt_id" => "18",
    "title" => "运营部",
    "pid" => "1",
    "update_eid" => "1",
    "update_time" => "2018-03-27 13:15:10",
],[
    "sys_dpt_id" => "26",
    "title" => "结算部",
    "pid" => "1",
    "update_eid" => "1",
    "update_time" => "2018-03-27 13:15:10",
]
];
//  [5] => array(5) {
//    ["sys_dpt_id"] => string(2) "26"
//    ["title"] => string(9) "结算部"
//    ["pid"] => string(1) "1"
//    ["update_eid"] => string(1) "1"
//    ["update_time"] => string(19) "2018-03-27 13:26:24"
//  }
//  [6] => array(5) {
//    ["sys_dpt_id"] => string(2) "27"
//    ["title"] => string(9) "保障组"
//    ["pid"] => string(2) "25"
//    ["update_eid"] => string(1) "1"
//    ["update_time"] => string(19) "2018-03-27 13:27:06"
//  }